package net.caixiaomi.info.ui.football;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baidu.mobstat.StatService;
import com.google.gson.reflect.TypeToken;

import net.caixiaomi.info.R;
import net.caixiaomi.info.WebViewActivity;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseAlertDialog;
import net.caixiaomi.info.base.BaseFragment;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.base.quickadapter.entity.MultiItemEntity;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.interfaces.PlayFootballItemChangeListener;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.ElementCellModel;
import net.caixiaomi.info.model.FootBallHeaderModel;
import net.caixiaomi.info.model.MatchItem;
import net.caixiaomi.info.model.MatchPlaysList;
import net.caixiaomi.info.model.PlayFootballItem;
import net.caixiaomi.info.model.PlayFootballList;
import net.caixiaomi.info.model.PlayFootballModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.dialog.BlendDialogFragment;
import net.caixiaomi.info.ui.dialog.FootballMatchIntroduceDialogFragment;
import net.caixiaomi.info.ui.dialog.HalfAndAllDialogFragment;
import net.caixiaomi.info.ui.dialog.MatchFilterDialogFragment;
import net.caixiaomi.info.ui.dialog.ScoreDialogFragment;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

import static android.R.id.list;
import static com.alibaba.fastjson.JSON.parseObject;

/**
 * Created by suntian on 2018/8/21.
 */

public class PlayFootballFragment extends BaseFragment implements PlayFootballItemChangeListener, BaseQuickAdapter.OnItemChildClickListener{

    private int mType;

    @Override
    protected int fragmentLayout() {
        return R.layout.act_play_football;
    }

    @Override
    protected void onFragmentCreated(View view, @Nullable Bundle savedInstanceState) {
        mEmptyView = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.empty, null);
        mEmptyView.setText(R.string.C_MESSAGE_EMPTY);
        mRefresh.setEnableRefresh(false);
        mListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new FootballAdapter(mType, null);
        mAdapter.openLoadAnimation();
        mAdapter.setOnItemChildClickListener(this);
        mListView.setAdapter(mAdapter);
        mAdapter.setEnableLoadMore(true);
        mAdapter.setListener(this);

        loadData();

        filterConditions();
    }

    public void setType(int type){
        mType=type;
    }

    @BindView(R.id.refresh)
    SmartRefreshLayout mRefresh;

    @BindView(list)
    RecyclerView mListView;

    @BindView(R.id.progress)
    CircularProgressBar mProgress;
    //选择提示
    @BindView(R.id.text)
    TextView mSelectTip;
    //总共场次
    @BindView(R.id.total)
    TextView mTotalNum;
    private FootballAdapter mAdapter;

//    private int mType = Constants.TYPE_VICTORY_AND_DEFEAT;
    private String mLotteryClassifyId = "";
    private String mPlayClassifyId = "";

    private TextView mEmptyView;
    private List<MultiItemEntity> mSelectd = new ArrayList<>();
    private List<MatchItem> mMatchList;
    private String mLeagueId = "";
    private int mCurrentClickItemPosition = -1;

    @OnClick(R.id.btn_delete)
    void toDelete() {
        if (mSelectd.isEmpty()) {
            ToastUtil.s(R.string.C_NO_SELECT_MATCH);
            return;
        }
        BaseAlertDialog dialog = new BaseAlertDialog(getActivity());
        dialog.setMessage(R.string.C_CLEAR_SELECT_MATCH);
        dialog.setPositiveButton(R.string.C_CLEAR, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearSelect();
                mSelectd.clear();
                mSelectTip.setText(R.string.C_FOOTBALL_SELECT_TIP);
            }
        });
        dialog.setNegativeButton(R.string.C_BACK, null);
        dialog.show();

    }

    @OnClick(R.id.btn_done)
    void toDone() {
        try {
            if (mSelectd.isEmpty()) {
                ToastUtil.s(R.string.C_NO_SELECT_MATCH);
                return;
            }
            if (mSelectd.size() == 1) {
                PlayFootballItem model = (PlayFootballItem) mSelectd.get(0);
                boolean isSupportSingle = true;
                List<MatchPlaysList> matchPlays = model.getMatchPlays();
                List<ElementCellModel> selectCell = model.getSelectCell();
                for (MatchPlaysList matchPlaysList : matchPlays) {
                    for (ElementCellModel cellModel : selectCell) {
                        if (TextUtils.equals(cellModel.getPlayType(), matchPlaysList.getPlayType())) {
                            if (TextUtils.equals(matchPlaysList.getSingle(), "0")) {
                                isSupportSingle = false;
                            }
                        }
                    }
                }

                if (!isSupportSingle) {
                    ToastUtil.s(R.string.C_SELECT_NEED_MATCH);
                    return;
                }
            }

            AppHelper.sendStatistics("changciqdzc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{getTitleFormType()});
            String strData = JSON.toJSONString(mSelectd);
            Intent intent = new Intent(getActivity(), FootballTakeOrderActivity.class);
            intent.putExtra("playType", String.valueOf(mType));
            intent.putExtra("lotteryClassifyId", mLotteryClassifyId);
            intent.putExtra("playClassifyId", mPlayClassifyId);
            intent.putExtra("data", strData);
            startActivity(intent);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String getTitleFormType() {
        String title = "";
        switch (mType) {
            case Constants.TYPE_VICTORY_AND_DEFEAT:
                title = getString(R.string.C_VICTORY_AND_DEFEAT);
                break;
            case Constants.TYPE_VICTORY_AND_DEFEAT_1:
                title = getString(R.string.C_VICTORY_AND_DEFEAT_1);
                break;
            case Constants.TYPE_ALL_GOALS:
                title = getString(R.string.C_ALL_GOALS);
                break;
            case Constants.TYPE_HALF_AND_ALL:
                title = getString(R.string.C_HALF_AND_ALL);
                break;
            case Constants.TYPE_SCORE:
                title = getString(R.string.C_SCORE);
                break;
            case Constants.TYPE_BLEND:
                title = getString(R.string.C_BLEND);
                break;
            case Constants.TYPE_2_IN_1:
                title = getString(R.string.C_2_IN_1);
                break;
        }
        return title;
    }

    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("playType", String.valueOf(mType));
        params.put("leagueId", mLeagueId);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<PlayFootballModel>> matchList = requestService.getMatchList(params);
        matchList.enqueue(new ResponseCallback<BaseCallModel<PlayFootballModel>>(getActivity()) {
            @Override
            public void onSuccess(BaseCallModel<PlayFootballModel> data) {
                mSelectd.clear();
                mProgress.setVisibility(View.GONE);
                PlayFootballModel model = data.data;
                if (model != null) {
                    mLotteryClassifyId = model.getLotteryClassifyId();
                    mPlayClassifyId = model.getLotteryPlayClassifyId();
                    mTotalNum.setText(getString(R.string.C_ALL_MATCH_COUNT, model.getAllMatchCount()));
                    List<PlayFootballItem> hotPlayList = model.getHotPlayList();
                    List<MultiItemEntity> dataList = new ArrayList<>();
                    if (!hotPlayList.isEmpty()) {
                        FootBallHeaderModel headerModel = new FootBallHeaderModel(getString(R.string.C_MATCH_HOT));
                        headerModel.setHot(true);
                        headerModel.setSubItems(hotPlayList);
                        dataList.add(headerModel);
                    }
                    List<PlayFootballList> playList = model.getPlayList();
                    StringBuilder stringBuilder = new StringBuilder();
                    for (PlayFootballList list : playList) {
                        stringBuilder.setLength(0);
                        stringBuilder.append(list.getMatchDay()).append(" ").append(getString(R.string.C_ALL_MATCH_COUNT, String.valueOf(list.getPlayList().size())));
                        FootBallHeaderModel headerModel = new FootBallHeaderModel(stringBuilder.toString());
                        headerModel.setSubItems(list.getPlayList());
                        dataList.add(headerModel);
                    }

                    if (dataList.isEmpty()) {
                        mAdapter.setEmptyView(mEmptyView);
                    }

                    mAdapter.setNewData(dataList);
                    mAdapter.expandAll();
                }
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 获取赛事列表
     */
    private void filterConditions() {
        JSONObject params = new JSONObject();
        params.put("time", String.valueOf(System.currentTimeMillis()));
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<List<MatchItem>>> filterConditions = requestService.filterConditions(params);
        filterConditions.enqueue(new ResponseCallback<BaseCallModel<List<MatchItem>>>(getActivity()) {
            @Override
            public void onSuccess(BaseCallModel<List<MatchItem>> data) {
                mMatchList = data.data;
            }

            @Override
            public void onFail(ResponseError error) {
            }

            @Override
            public void onError() {
            }
        });
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.filter:
                AppHelper.sendStatistics("shaixuansszc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{getTitleFormType()});
                showMatchFilterDialog();
                break;
            case R.id.btn_help:
                AppHelper.sendStatistics("saishibangzhuzc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{getTitleFormType()});
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(Constants.BASE_H5_URL).append(getString(R.string.H5_PLAY_INTRODUCE));
                String url = stringBuilder.toString();
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url", url);
                startActivity(intent);
                break;

        }
        return true;
    }

    @Override
    public void onPostEvent(CommonEvent event) {
        switch (event.getWhat()) {
            case EventWhat.EVENT_FOOTBALL_MATCH_FILTER:
                handleMatchFilter(event.getMessage());
                AppHelper.sendStatistics("sszhongleizc", new String[]{getString(R.string.C_PLAY_GAME)}, new String[]{mLeagueId});
                loadData();
                break;
            case EventWhat.EVENT_FOOTBALL_SELECT_DONE:
                handleSelectItem(event.getMessage());
                break;

        }
    }

    private void clearSelect() {
        try {
            Iterator<MultiItemEntity> iterator = mSelectd.iterator();
            while (iterator.hasNext()) {
                PlayFootballItem model = (PlayFootballItem) iterator.next();
                List<ElementCellModel> selectCells = model.getSelectCell();
                for (ElementCellModel cellModel : selectCells) {
                    cellModel.setSelected(false);
                }
                model.getSelectCell().clear();
            }
            mAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleMatchFilter(String message) {
        try {
            JSONObject object = parseObject(message);
            JSONArray dataArray = object.getJSONArray("data");
            mMatchList = JSON.parseObject(dataArray.toString(), new TypeToken<List<MatchItem>>() {
            }.getType());

            StringBuilder stringBuilder = new StringBuilder();
            for (MatchItem item : mMatchList) {
                if (item.isSelect()) {
                    stringBuilder.append(item.getLeagueId()).append(",");
                }
            }
            if (!TextUtils.isEmpty(stringBuilder)) {
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            }
            mLeagueId = stringBuilder.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showMatchFilterDialog() {
        if (mMatchList != null) {
            String strData = JSON.toJSONString(mMatchList);
            MatchFilterDialogFragment dialog = new MatchFilterDialogFragment();
            Bundle bundle = new Bundle();
            bundle.putString("data", strData);
            dialog.setArguments(bundle);
            dialog.show(getActivity().getSupportFragmentManager(), MatchFilterDialogFragment.class.getName());
        }
    }

    /**
     * 停售
     */
    private void showSoldOutDialog() {
        BaseAlertDialog dialog = new BaseAlertDialog(getActivity());
        dialog.setMessage(R.string.C_SOLD_OUT_TIP);
        dialog.setPositiveButton(R.string.C_I_KNOW, null);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    @Override
    public boolean canChange(PlayFootballItem item) {
        boolean hasSelect = item.getSelectCell() != null && !item.getSelectCell().isEmpty();

        if (!hasSelect) {//如果当前没有选中的cell，检查是否可以添加到选中列表中
            if (!mSelectd.contains(item)) {
                if (mSelectd.size() >= Constants.FOOTBALL_MAX_SELECT_NUM) {
                    ToastUtil.s(R.string.C_SELECT_MATCH_15);
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void onItemChangeListener(PlayFootballItem item) {
        try {
            boolean hasSelect = item.getSelectCell() != null && !item.getSelectCell().isEmpty();

            if (!hasSelect) {
                mSelectd.remove(item);
            } else {
                if (!mSelectd.contains(item)) {
                    mSelectd.add(item);
                }
            }

            if (mSelectd.isEmpty()) {
                mSelectTip.setText(R.string.C_FOOTBALL_SELECT_TIP);
            } else {
                String text = getString(R.string.C_SELECT_MATCH_COUNT, mSelectd.size());
                int start = text.indexOf(String.valueOf(mSelectd.size()));
                SpannableString spannableString = new SpannableString(text);
                spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.orange_primary)), start, start + String.valueOf(mSelectd.size()).length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
                mSelectTip.setText(spannableString);
            }
            mAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            DialogFragment dialog = null;
            String strData = "";
            PlayFootballItem item = (PlayFootballItem) mAdapter.getData().get(position);
            if (view.getId() == R.id.content) {
                strData = item.getMatchId();
                dialog = new FootballMatchIntroduceDialogFragment();
            } else if (view.getId() == R.id.btn_float) {
                showSoldOutDialog();
                return;
            } else {
                mCurrentClickItemPosition = position;
                strData = JSON.toJSONString(item);
                int playType = Integer.valueOf(item.getPlayType());
                if (playType == Constants.TYPE_HALF_AND_ALL) {
                    dialog = new HalfAndAllDialogFragment();
                } else if (playType == Constants.TYPE_SCORE) {
                    dialog = new ScoreDialogFragment();
                } else if (playType == Constants.TYPE_BLEND) {
                    dialog = new BlendDialogFragment();
                }

            }
            Bundle bundle = new Bundle();
            bundle.putString("data", strData);
            dialog.setArguments(bundle);
            dialog.show(getActivity().getSupportFragmentManager(), dialog.getClass().getName());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleSelectItem(String message) {
        try {
            if (!TextUtils.isEmpty(message) && mCurrentClickItemPosition != -1) {
                PlayFootballItem oldItem = (PlayFootballItem) mAdapter.getData().get(mCurrentClickItemPosition);
                PlayFootballItem newItem = parseObject(message, new TypeReference<PlayFootballItem>() {
                });
                mCurrentClickItemPosition = -1;
                if (newItem.getSelectCell() != null) {
                    if (!mSelectd.contains(oldItem) && !newItem.getSelectCell().isEmpty()) {
                        if (mSelectd.size() >= Constants.FOOTBALL_MAX_SELECT_NUM) {
                            ToastUtil.s(R.string.C_SELECT_MATCH_15);
                            return;
                        }
                    }
                    oldItem.setSelectCell(newItem.getSelectCell());
                    oldItem.setMatchPlays(newItem.getMatchPlays());
                }
                onItemChangeListener(oldItem);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
